<?php

namespace App\Services\UserInviteInfo;

use App\Models\User;
use App\Models\Product;
use Illuminate\Support\Str;
use Intervention\Image\Gd\Font;
use Illuminate\Support\Facades\File;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Storage;

class MakeUserInvitePoster
{
	/**
	 * @var User
	 */
	protected $user;
	
	protected $channel = 'wap'; // wap, mini
	
	public function __construct(User $user, $channel = 'wap')
	{
		$this->user = $user;
		$this->channel = $channel;
	}
	
	protected function getPosterName()
	{
		return "poster-user-{$this->user->id}.png";
	}
	
	protected function getRemotePosterDir()
	{
		return 'images/wap-user-invite-posters';
	}
	
	protected function getRemotePosterSavePath()
	{
		return $this->getRemotePosterDir() . '/' . $this->getPosterName();
	}
	
	protected function getLocalPosterSavePath(string $name)
	{
		$localPath = public_path('temp/wap-user-invite-posters');
		if (! File::isDirectory($localPath)) {
			File::makeDirectory($localPath, 755, true, true);
		}
		return "{$localPath}/{$name}.png";
	}
	
	public function make()
	{
		if (Storage::exists($this->getRemotePosterSavePath())) {
			return Storage::url($this->getRemotePosterSavePath());
		}
		
		$posterDir = $this->getRemotePosterDir();
		$posterName = $this->getPosterName();
		
		$back = Image::make(oss('images/wap/wap-user-poster-bg.png'));
		$name = Str::limit($this->user->name, 6);
		$qrcode = $this->user->inviteQrcode();
		$qrcode = Image::make($qrcode)->resize(376, 376);
		
		Image::canvas(750, 1192, '#FFFFFF')
			->insert($back, 'top', 0, 0)
			->text($name, 150, 230, function (Font $font) {
				$font->file(public_path('font/MSYH.TTF'));
				$font->color('#000000');
				$font->size(40);
			})
			->insert($qrcode, 'top-left', 190, 390)
			->save($this->getLocalPosterSavePath($posterName));
		
		// move to oss.
		Storage::putFileAs($posterDir, $this->getLocalPosterSavePath($posterName), $posterName);
		
		// remove local poster.
		File::delete($this->getLocalPosterSavePath($posterName));
		
		return Storage::url("{$posterDir}/{$posterName}");
	}
}
